﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace WenSkin.Controls
{
    public class WenDataGridViewComboBoxCell : DataGridViewTextBoxCell
    {

        public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
            if (this.OwningColumn is WenDataGridViewComboBoxColumn column)
                if (DataGridView.EditingControl is WenDataGridViewComboBoxCellEdit edit)
                {
                    edit.Text = this.Value?.ToString();
                    edit.Items.Clear();
                    edit.Items.AddRange(column.Items.ToArray());
                }
        }

        public override Type ValueType => typeof(string);
        public override Type EditType => typeof(WenDataGridViewComboBoxCellEdit);
        public override object DefaultNewRowValue => "";

        class WenDataGridViewComboBoxCellEdit : WenComboBox, IDataGridViewEditingControl
        {
            public DataGridView EditingControlDataGridView { get; set; }
            public object EditingControlFormattedValue
            {
                get => this.Text;
                set
                {
                    if (value is string v)
                        this.Text = v;
                    else this.Text = "";
                }
            }
            public int EditingControlRowIndex { get; set; }
            public bool EditingControlValueChanged { get; set; }

            public Cursor EditingPanelCursor => base.Cursor;

            public bool RepositionEditingControlOnValueChange => false;

            public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
            {
                this.Font = dataGridViewCellStyle.Font;
                this.ForeColor = dataGridViewCellStyle.ForeColor;
                this.BackColor = dataGridViewCellStyle.BackColor;
            }

            public bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey)
            {
                return dataGridViewWantsInputKey;
            }

            public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
            {
                return EditingControlFormattedValue;
            }

            public void PrepareEditingControlForEdit(bool selectAll)
            {

            }
            protected override void OnTextChanged(EventArgs e)
            {
                base.OnTextChanged(e);
                EditingControlValueChanged = true;
                this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            }
        }
    }
}
